<template>
  <div>
    <van-nav-bar title="登录" />
    <div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="user.mobile"
          required
          name="mobile"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[
            {
              required: true,
              message: '请填写手机号',
              pattern: /^1[3-9]\d{9}$/,
            },
          ]"
        />
        <van-field
          v-model="user.code"
          required
          type="password"
          name="code"
          label="密码"
          placeholder="请输入密码"
          :rules="[
            {
              required: true,
              message: '请填写密码',
              pattern: /^\d{6}$/,
            },
          ]"
        />
        <div style="margin: 16px">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            :disabled="isLoading"
            :loading="isLoading"
            >提交</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { reqLogin } from "@/api";
import { Notify } from "vant";
import { setToken } from "@/utils/token.js";
export default {
  name: "Login",
  data() {
    return {
      user: {
        mobile: "",
        code: "",
      },
      isLoading: false,
    };
  },
  methods: {
    async onSubmit() {
      try {
        this.isLoading = true;
        const res = await reqLogin(this.user);
        if (res.status == 201) {
          console.log(res.data);
          Notify({ type: "success", message: "登录成功！" });
          setToken(res.data.data.token);
          localStorage.setItem("refresh_token", res.data.data.refresh_token);
          this.$router.push({
            path: "/layout/home",
          });
        }
      } catch (error) {
        Notify({ type: "warning", message: "手机号或者验证码不正确" });
      }
      this.isLoading = false;
    },
  },
};
</script>

<style lang="less">
.van-nav-bar {
  background-color: #1989fa;
}
</style>
